package _14_网络编程._2_TCP编程.单线程;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;


public class Client {

    public static void main(String[] args) throws IOException {

        Socket socket;
        System.out.println("Client localhost : " + InetAddress.getLocalHost() + "," + System.currentTimeMillis());
        socket = new Socket(InetAddress.getLocalHost(),56799);

        try(InputStream inputStream = socket.getInputStream()){
            try(OutputStream outputStream = socket.getOutputStream()){
                handle(inputStream,outputStream);
            }
        }

        socket.close();



    }

    public static void handle(InputStream inputStream, OutputStream outputStream) throws IOException {

        String str;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,StandardCharsets.UTF_8));
        Scanner scanner = new Scanner(System.in);

        System.out.println("[server] " + bufferedReader.readLine() + "," + System.currentTimeMillis());

        int i = 0;
        while(true){
            System.out.println("client :: ========= start " + i);
            System.out.println(">>>" + "," + System.currentTimeMillis());
            str = scanner.nextLine();
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            bufferedWriter.flush();

            str = bufferedReader.readLine();
            System.out.println(str);
            if (str.equals("bye")) {
                break;
            }
            System.out.println("client :: ========= end " + i);
            i++;
        }
    }
}
